/**
 * Created by xz on 2017/9/20.
 */
console.log('musicList');
$('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
    $(this).prev().focus();
});
$('#startDate').datepicker('update');
$('#endDate').datepicker('update');

console.log(typeQuery());

var selectionIds = [];  //保存选中ids
// 初始化table
var $table =  $("#musci_table").bootstrapTable({
    'url': '/community/music/findMusicFromLibrary',
    'queryParams': queryParams,
    'cache': false,
    'toolbar': $('div[data-name="btnCtl"]'),
    // 'toolbarAlign': 'right',
    'striped': true,
    'sidePagination': 'server',
    'pagination': true,
    'sortable': true, //是否启用排序
    'sortOrder': "asc", //排序方式
    'pageSize': globalPageSize,
    'pageList': [],
    'clickToSelect': true,
    'singleSelect': false,
    'maintainSelected': true,
    'smartDisplay': true,
    'ajaxOptions':{
        headers: {"Authorization": localStorage.token}
    },
    'responseHandler': function (resb) {
        $.each(resb.data.rows, function (i, row) {
            row.checkStatus = $.inArray(row.musicId, selectionIds) != -1;  //判断当前行的数据id是否存在与选中的数组，存在则将多选框状态变为true
        });
        // return resb;
        console.log(resb);
        return {
            'total': resb.data.total,
            'rows': resb.data.rows
        }
    },
    'onCheckAll': function () {
        $("#dataAddType").removeAttr("disabled");
    },
    'onUncheck': function () {
        $("#dataAddType").attr("disabled", 'true');
    },
    'onCheck': function () {
        $("#dataAddType").removeAttr("disabled");
    },
    'onUncheck': function () {
        $("#dataAddType").attr("disabled", 'true');
    },
    // 'onPageChange': function () {
    //     if ($("#musci_table").bootstrapTable('getSelections')[0]) {
    //         $("#musci_table").bootstrapTable('uncheckBy', {
    //             field: 'playCount',
    //             values: [$("#musci_table").bootstrapTable('getSelections')[0].playCount]
    //         });
    //     }
    // },
    'columns': [{
        'field': 'checkStatus',
        'checkbox': true
    },
        {
            'field': 'musicId',
            'title': 'ID',
            'align': 'center',
            'class': 'hide musicId'
        },{
            'title': '序号',
            'align': 'center',
            'formatter': function (value, row, index) {
                return index+1;
            }
        },{
            'field': 'createDate',
            'title': '创建时间',
            'align': 'center'
        },
        {
            'field': 'albumCoverAddress',
            'title': '专辑封面',
            'align': 'center',
            'formatter': function (albumCoverAddress) {
                return  albumCoverAddress != null ?"<image style='width: 70px;' src="+albumCoverAddress+">" : null;
            }
        },
        {
            // 'field': 'musicName,singer,songLength',
            'title': '音乐信息',
            'align': 'center',
            'formatter': function (value, row, index) {
                var html = "<p>"+row.musicName+"</p><p>"+row.singer+"</p><p>"+(row.songLength == null ? '-' : row.songLength)+"</p>";
                return html;
            }
        },
        {
            'field': 'videoAddress',
            'title': '视频地址',
            'align': 'center'
        },
        {
            'field': 'playCount',
            'title': '总使用次数',
            'align': 'center'
        },
        {
            'title': '操作',
            'align': 'center',
            'formatter': function () {
                var  html = "<button data-type='update' class='btn btn-sm btn-success update' data-toggle='modal' data-target='#updateModal' style='margin-right: 10px'>修改</button><button data-type='delete' class='btn btn-sm btn-success delete' data-toggle='modal' data-target='#deleteModal'>删除</button>"
                return html;
            }
        }
    ]
});

//选中事件操作数组
var union = function(array,ids){
    $.each(ids, function (i, id) {
        if($.inArray(id,array)==-1){
            array[array.length] = id;
        }
    });
    return array;
};
//取消选中事件操作数组
var difference = function(array,ids){
    $.each(ids, function (i, id) {
        var index = $.inArray(id,array);
        if(index!=-1){
            array.splice(index, 1);
        }
    });
    return array;
};
var _ = {"union":union,"difference":difference};
//绑定选中事件、取消事件、全部选中、全部取消
$table.on('check.bs.table check-all.bs.table uncheck.bs.table uncheck-all.bs.table', function (e, rows) {
    var ids = $.map(!$.isArray(rows) ? [rows] : rows, function (row) {
        return row.musicId;
    });
    func = $.inArray(e.type, ['check', 'check-all']) > -1 ? 'union' : 'difference';
    selectionIds = _[func](selectionIds, ids);
});

//请求服务数据时所传参数
function queryParams(params){
    return {
        'createDateS': $('#startDate').val(),
        'createDateE': $('#endDate').val(),
        'name': $('#name_search').val(),
        'typeId': ($('#type_search').val() == null ? '2aeded1129784decbab8b8bf18329c7c' : $('#type_search').val()),
        limit : params.limit, //每一页的数据行数，默认是上面设置的10(pageSize)
        offset : params.offset/params.limit+1 //当前页面,默认是上面设置的1(pageNumber)
    }
}

/**
 * 音乐查询ajax
 */
function musicQuery() {
    if (($("#name_search").val() == '')) {
        $('#musci_table').bootstrapTable('refreshOptions', {pageNumber: 1, pageSize: globalPageSize});
    } else {
        $.ajaxSetup({cache:false});
        $.ajax({
            type: "POST",
            url: "/community/music/findMusicFromLibrary",
            data: {
                'createDateS': $('#startDate').val(),
                'createDateE': $('#endDate').val(),
                'name': $('#name_search').val(),
                'typeId': $('#type_search').val(),
                'offset': 0,
                'limit': globalPageSize
            },
            dataType: 'json',
            'sidePagination': 'server',
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", localStorage.token);
            },
            success: function (resb) {
                if (resb.data.rows != 0) {
                    $("#musci_table").bootstrapTable('load', {'total': resb.data.total, 'rows': resb.data.rows});
                } else {
                    $("#musci_table").bootstrapTable('removeAll');
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }
    return false;
}

/**
 * 分类查询ajax
 */
function typeQuery() {
    $.ajaxSetup({cache:false});
    $.ajax({
        type: "GET",
        url: "/community/musictype/findMusictypeList?mark=false&offset=1&limit=100",
        dataType: 'json',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        success: function (resb) {
           console.log(resb);
           if(resb.success) {
               var data = resb.data.rows;
               $('#type_search').empty().append("<option value='2aeded1129784decbab8b8bf18329c7c'>不限</option>");
               $('#addModal .addTypeList').empty();
               $('#updateModal .updateTypeList').empty();
               for(var i = 0; i < data.length; i++) {
                   $('#type_search').append("<option value="+data[i].typeId+">"+data[i].typeName+"</option>");
                   $('#addModal .addTypeList').append("<label class='checkbox-inline'><input type='checkbox'  value="+data[i].typeId+"> "+data[i].typeName+"</label>");
                   $('#updateModal .updateTypeList').append("<label class='checkbox-inline'><input type='checkbox'  value="+data[i].typeId+"> "+data[i].typeName+"</label>");
               }
           }else {
               alert(resb.message);
           }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
    return false;
}

/**
 * 音乐操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {adminId: int}]
 * @param async/scync [default async]
 */
function adminManagement(action, data, async) {
    var url = null;
    (async === false) ? async = false : async = true;
    if (action === 'add') {
        url = '/community/music/addMusicToLibrary';
    } else if (action === 'update') {
        url = '/community/music/updateMusic';
    } else if(action === 'delete') {
        url = '/community/music/deleteMusicFromLibrary';
    }

    $.ajaxSetup({cache:false});
    return $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(data),
        dataType: 'json',
        async: async,
        contentType:'application/json; charset=UTF-8',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        success: function (resb) {
            alert(resb.message);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // console.log(XMLHttpRequest, textStatus, errorThrown);
            if(textStatus=='timeout'){
                ajaxTimeOut.abort(); //取消请求
                alert("请求超时");
            };
            alert(textStatus);
        }
    });
};

/**
 * 条件查询音乐
 */
$("#dataSearch").click(function () {
    return musicQuery();
});

/**
 * 新增模态框显示
 */
$("#addModal").on('show.bs.modal', function () {
    $(this).find('input[type=password]').val("");
    $(this).find('input[type=text]').val("");
    // $(this).find('select ').val("");
});

$(document).on('click', '.delete, .update', function () {
    $("#musci_table").bootstrapTable('uncheckAll');
    $("#musci_table").bootstrapTable('check', $(this).parent().parent().index());
    // $(this).parent().parent().find('input:checkbox').prop('checked', true);
    var tableData = $("#musci_table").bootstrapTable('getSelections');
    var table = {};
    console.log($("#musci_table").bootstrapTable('getSelections'));
    console.log($(this).parent().parent().find('.musicId').html());
    for(var i = 0; i < tableData.length; i++) {
        if($(this).parent().parent().find('.musicId').html() === tableData[i].musicId) {
            tableData[i][0] = true;
            table = tableData[i];
        }else {
            tableData[i][0] = false;
        }
    };

    if($(this).attr('data-type') === 'update') {
        $("#updateModal").modal('show');
        $('#update_musicId').val(table.musicId);
        $('#show_image1').attr('src',table.albumCoverAddress);
        $('#update_imageUrl').val(table.albumCoverAddress);
        $('#update_musicFile').val(table.musicAddress);
        $('#update_videoFile').val(table.videoAddress);
        $('#update_musicName').val(table.musicName);
        $('#update_singerName').val(table.singer);
        $('#update_playCount').val(table.playCount);
        $('#update_musicLength').val(table.songLength);
    }else {
        $("#deleteModal").modal('show');
        var html = '你确定要删除音乐: <span>' + table.musicName + '</span>?';
        $("#deleteModal").find('div.modal-body').empty().append(html);
    };
});



/**
 * 添加到分类模态框显示
 */
$('#dataAddType').click(function () {
    if(selectionIds.length > 0) {
        $('#addTypeModal').modal('show');
    }else {
        alert('请选择至少一项')
    }
});

$('#addToType').click(function () {
    $('#addTypeModal').modal('hide');
    $.ajax({
        url: '/community/musictype/addMusicToTypeBatch' ,
        type: "POST",
        data: JSON.stringify({
            "musicId": selectionIds,
            "typeId": "1"
        }),
        dataType: 'json',
        contentType:'application/json; charset=UTF-8',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        success: function (resb) {
            console.log(resb);
            alert(resb.message);
            $("#musci_table").bootstrapTable("refresh");
            selectionIds = [];
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // console.log(XMLHttpRequest, textStatus, errorThrown);
            if(textStatus=='timeout'){
                ajaxTimeOut.abort(); //取消请求
                alert("请求超时");
            };
            alert(textStatus);
        }
    })
});

/**
 * 文件上传
 */
//获取添加文件按钮里面的所有文件并发给后台
$('.addFiles, .updateFiles').on('change',function (e) {
    // var paths = document.getElementById("addFiles").files;
    var paths = this.files;
    console.log(this);
    if(paths.length==0)
    {
        alert("请选择文件");
        return;
    }
    //我们可以预先定义一个FormData对象
    var formData=new FormData();
    // formData.append("file",paths);
    for(var i=0;i<paths.length;i++)
    {
        //将每个文件设置一个string类型的名字，放入到formData中，这里类似于setAttribute("",Object)
        formData.append("file",paths[i]);
    }
    var target = $(this).parents('.form-group').find(':text');
    var img = $(this).parents('.form-group').find('img');
    addFiles(formData, target, img);
    return false;
});

//添加文件的ajax
function addFiles(formData, target, img) {
    return $.ajax({
        url: '/common/uploadFile',
        type: 'POST',
        cache: false,
        data:formData,
        //这个参数是jquery特有的，不进行序列化，因为我们不是json格式的字符串，而是要传文件
        processData: false,
        //注意这里一定要设置contentType:false，不然会默认为传的是字符串，这样文件就传不过去了
        contentType: false,
        success:function(resp){
            alert("文件上传成功");
            var data = resp.data;
            target.val(data.url);
            if(img) {
                img.attr('src', data.url)
            };
            if(data.format === 'mp3') {
                $('#audio').attr('src', data.url);
                document.getElementById("audio").addEventListener("canplay", function() {
                    var time = parseInt(audio.duration);
                    console.log(time);
                    var timeStr = (parseInt(time/60) < 10 ? '0'+ parseInt(time/60) : parseInt(time/60)) + ':' + time%60;
                    $('#add_musicLength, #update_musicLength').val(timeStr);
                })
            };
        },
        error:function (err) {

        }
    });
};

/**
 * 新增,更新,删除角色表单提交
 */
$("#addForm, #updateForm, #deleteForm, #addTypeForm").submit(function () {
    var type = $(this).data("type"),
        $modal = $("#" + type + "Modal"),
        tableData = $("#musci_table").bootstrapTable('getSelections')[$("#musci_table").bootstrapTable('getSelections').length-1],
        $that = $(this);

    // 模式选择,设置不同的data和url
    if (type === 'delete') {
        data = {
            'musicId': tableData.musicId
        };
    } else if (type === 'add') {
        var obj = jQuery("#addForm").validationEngine('validate', {
            promptPosition: "centerRight",
            autoPositionUpdate: true,
            validationEventTrigger:'blur',
            binded:true,
            showOneMessage:true
        });
        if (!obj) {
            return false;
        }
        var addType = [];
        for(var i = 0; i < $('.addTypeList input').length; i++) {
            if($('.addTypeList input').eq(i).prop('checked') === true) {
                addType.push($('.addTypeList input').eq(i).val())
            }
        };
        data = {
            'musiclibrary': {
                'musicName': trim($('#add_musicName').val()),
                'singer': trim($('#add_singerName').val()),
                'albumCoverAddress': $('#add_imageUrl').val(),
                'songLength': trim($('#add_musicLength').val()),
                // 'videoAddress': $('#add_videoFile').val(),
                'musicAddress': $('#add_musicFile').val()
            },
            'typeId': addType
        };
    } else if (type === 'update') {
        data = {
            'musicId': $('#update_musicId').val(),
            'musicName': trim($('#update_musicName').val()),
            'singer': trim($('#update_singerName').val()),
            'albumCoverAddress': $('#update_imageUrl').val(),
            'songLength': trim($('#update_musicLength').val()),
            // 'videoAddress': $('#update_videoFile').val(),
            'musicAddress': $('#update_musicFile').val(),
            'playCount': $('#update_playCount').val()
        };
    }

    // $('#addModal').modal('hide');
    // $('#updateModal').modal('hide');
    // $('#deleteModal').modal('hide');
    $modal.modal('hide');
    // 完成ajax后刷新表格数据
    adminManagement(type, data).done(function () {
        $("#musci_table").bootstrapTable("refresh");
        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
        $that.parents('.modal-content').find('form')[0].reset();
    });

    // 阻止表格冒泡事件
    return false;
});

//去除字符串左右空格
function trim(s){
    return s.replace(/(^\s*)|(\s*$)/g, "");
}
